/**
 * @description  : cordova 平台api适配
 * @descriptionDetail : cordova 平台api适配
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 19:32:17
 */

import util from '../common/util.js'
/**
 * 设备的定位服务是否开启
 */
const isLocationEnabled = function() {
	return new Promise((res, rej) => {
		cordova.plugins.diagnostic.isLocationEnabled(function(enabled) {
			res(enabled)
		}, function(error) {
			rej(error)
		});
	});
};
/**
 * app是否能够访问设备位置..
 */
const isLocationAvailable = function() {
	return new Promise((res, rej) => {
		cordova.plugins.diagnostic.isLocationAvailable(function(available) {
			res(available)
		}, function(error) {
			rej(error)
		});
	});
}
/**
 * 获取app定位权限
 */
const requestLocationAuthorization = function() {
	return new Promise((resolve, reject) => {
		cordova.plugins.diagnostic.requestLocationAuthorization(function(status) {
			switch (status) {
				case cordova.plugins.diagnostic.permissionStatus.NOT_REQUESTED:
					// Modal.alert('提示',"权限请求 NOT_REQUESTED");
					resolve(false)
					break;
				case cordova.plugins.diagnostic.permissionStatus.GRANTED:
					// Modal.alert('提示',"权限请求准许");
					resolve(true)
					break;
				case cordova.plugins.diagnostic.permissionStatus.DENIED:
					// Modal.alert('提示',"权限请求被拒绝");
					resolve(false)
					break;
				case cordova.plugins.diagnostic.permissionStatus.DENIED_ALWAYS:
					// Modal.alert('提示',"权限请求被永远拒绝");
					resolve(false)
					break;
			}
		}, function(error) {
			reject(error)
			console.error(error)
		});
	})
}

let amapAndroidConfig = {
	interval: 2000, // 连续定位时间间隔（ms）
	androidAccuracy: 1, // 精确度 0. Battery_Saving 1. Hight_Accuracy, 2. Device_Sensors
	needAddress: true, // 是否返回地址信息
};

let amapIosConfig = {
	// ios配置
	locationTimeout: 10, // 定位Timeout(s)
	reGeocodeTimeout: 10, // 地址信息Timeout(s)
	iosAccuracy: 1000, // 精确度(m)
	distanceFilter: 10, // 连续定位最小位移(m)
	watchWithReGeocode: false, // 连续定位是否返回地址信息
	iosBackground: true, // 后台定位
};

const doRealLocation = function() {
	return new Promise((resolve, reject) => {
		if (window.navigator.connection.type == "none") {

			let sApp;
			if (util.isAndroid()) {
				sApp = startApp.set({
					"action": "ACTION_MAIN",
					"category": "CATEGORY_DEFAULT",
					"package": "com.autonavi.minimap",
					"uri": "androidamap://viewMap?sourceApplication=appname",
				});
			} else {
				sApp = startApp.set("iosamap://viewMap?sourceApplication=applicationName");
			}
			sApp.start(function() {

			}, function(error) {
				console.log(error);
			});
		} else {
			AmapLocation.getCurrentPosition(
				util.isIOS() ? amapIosConfig : amapAndroidConfig,
				x => {
					let s = {
						accuracy: x.accuracy,
						altitude: x.altitude,
						altitudeAccuracy: x.altitudeAccuracy,
						heading: x.heading,
						latitude: x.latitude,
						longitude: x.longitude,
						speed: x.speed,
						address: x.address,
						date: x.date,
						province: x.province,
						city: x.city,
						district: x.district,
						street: x.street,
						cityCode: x.cityCode,
						adCode: x.adCode,
						poiName: x.poiName,
						aoiName: x.aoiName,
					};
					resolve(s);
				},
				e => {
					if (e == 12) {
						reject({
							code: e,
							message: "缺少定位权限,请在设备的设置中开启APP的定位权限。",
						});
					} else if (e == 7) {
						reject({
							code: e,
							message: "地图提供商鉴权失败,请联系管理员检查。",
						});
					} else if (e == 4) {
						reject({
							code: e,
							message: "请求服务器过程中的异常,请检查设备网络是否通畅。",
						});
					} else {
						reject({
							code: e,
							message: "未分类错误。",
						});
					}
				}
			);
		}
	});
}
/**
 * 获取当前的地理位置、速度
 * @param {Object} type  wgs84返回gps 坐标，gcj02返回国测局坐标
 */
const geolocation = function(type) {
	return new Promise((resolve, reject) => {
		// 如果设备的定位服务未开启
		isLocationEnabled().then(enabled => {
			// 开启了 则定位
			if (enabled) {
				// 如果app未获取到定位权限 则尝试获取定位权限 不保证可以获取到
				isLocationAvailable().then(available => {
					if (!available) {
						requestLocationAuthorization().then(data => {
							if (data) {
								doRealLocation().then(data => {
									resolve(data)
								}).catch(error => {
									reject(error)
								});
							}
						}).catch(error => {
							reject(error)
						});
					} else {
						// 进行定位
						doRealLocation().then(data => {
							resolve(data)
						}).catch(error => {
							reject(error)
						});
					}
				});
			} else { // 手机的定位服务未开启则跳转到开启页面
				cordova.plugins.diagnostic.switchToLocationSettings();
			}
		});
	});
}

/**
 *  打开地图选择位置
 * @param {Object} latitude 
 * @param {Object} longitude
 */
const chooseLocation = function(latitude, longitude) {
	return new Promise(function(resolve, reject) {
		uni.chooseLocation({
			success: function(res) {
				resolve(res);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}
/**
 * 使用应用内置地图查看位置
 * @param {Object} latitude
 * @param {Object} longitude
 */
const openLocation = function(latitude, longitude) {
	return new Promise(function(resolve, reject) {
		uni.openLocation({
			latitude: Float(latitude),
			longitude: Float(longitude),
			success: function() {
				resolve(true);
			},
			fail() {
				reject(false);
			},
		});
	});
}

/**
 * 客户端(apk/ipa)的版本名称
 */
const getAppVersion = function() {
	return new Promise(function(resolve, reject) {
		let code = plus.runtime.version;
		resolve(code);
	});
}

/**
 * 客户端的版本号
 */
const getAppVersionCode = function() {
	return new Promise(function(resolve, reject) {
		let code = plus.runtime.versionCode;
		resolve(code);
	});
}
/**
 * 从本地相册选择图片或使用相机拍照
 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
 */
const chooseImage = function(maxSize) {
	return new Promise((resolve, reject) => {
		showActionSheet("", [{
			title: "拍照",
		}, {
			title: "从相册中选择",
		}, ], "取消", function(res) {
			imagePicker(res, maxSize);
		})
		let imagePicker = function(data, size) {
			let obj = [];
			if (data == 0) {
				let cameraOptions = {
					quality: 50,
					mediaType: Camera.MediaType.PICTURE,
				}; // see cordova camera docs
				MediaPicker.takePhoto(cameraOptions, function(media) {
					console.info("media:======" + JSON.stringify(media));
					resolve(media);
				}, function(e) {
					console.log(e)
					resolve(obj);
				});
			} else if (data == 1) {
				let args = {
					'selectMode': 100, // 101=picker image and video , 100=image , 102=video
					'maxSelectCount': size, // default 40 (Optional)
					'thumbnailQuality': 50,
					'thumbnailW': 200,
					'thumbnailH': 200,
					'quality': 70,
					'maxSelectSize': 188743680, // 1743680=.7M (Optional)
				};

				window.MediaPicker.getMedias(args, function(medias) {
					// medias [{mediaType: "image", path:'/storage/emulated/0/DCIM/Camera/2017.jpg', uri:"android retrun uri,ios retrun URL" size: 21993}]
					console.log(medias)
					for (let i = 0; i < medias.length; i++) {
						obj.push(medias[i]);
					}
					resolve(obj);
				}, function(e) {
					resolve(obj);
				});
			}
		}
	});
}

/**
 * 蓝牙热敏标签打印机
 * @param {String} img base64 图片 图片比例最好是 100 * 150
 * @param {String} width  100 
 * @param {String} height  150 
 */
const labelPrint = function(img, width = "100", height = "150") {
	return new Promise((resolve, reject) => {
		showActionSheet("", [{
			title: "佳博台式打印机",
		}, {
			title: "LM手持式打印机",
		}, ], "取消", function(res) {
			lgPrint(res, img, width, height);
		});
		let success = function(s) {
			resolve(s);
		};
		let err = function(s) {
			reject(s);
		};
		let lgPrint = function(data, imgStr, widthStr, heightStr) {
			let obj = [];
			if (data == 0) {
				window.sinowitsPrint.gPrint(success, err, imgStr, widthStr, heightStr);
			} else if (data == 1) {
				window.sinowitsPrint.lPrint(success, err, imgStr, widthStr, heightStr);
			}
		}
	});
}

/**
 * 图片转base64
 */
const extractThumbnail = function(media) {
	return new Promise(function(resolve, reject) {
		let base64;
		// 转换压缩质量宽度
		// media.thumbnailW = 800;
		// 转换压缩质量高度
		// media.thumbnailH = 800;
		// 缩略图质量
		media.thumbnailQuality = 50;
		// 图片质量
		media.quality = 50;
		MediaPicker.extractThumbnail(media, function(data) {
			base64 = 'data:image/jpeg;base64,' + data.thumbnailBase64;
			resolve(base64);
		}, function(e) {
			resolve(base64);
		});
	});
}

/**
 * 预览图片
 * @param {Object} urls 需要预览的图片链接列表
 */
const previewImage = function(urls) {
	return new Promise(function(resolve, reject) {
		uni.previewImage({
			urls: urls,
			success: function(data) {
				resolve(true);
			},
			fail: function(err) {
				reject(false);
			},
		})
	});
}

/**
 * 获取网络类型
 * wifi	wifi 网络	
 * 2g	2g 网络	
 * 3g	3g 网络	
 * 4g	4g 网络	
 * ethernet	有线网络	App
 * unknown	Android 下不常见的网络类型	
 * none	无网络
 * @param {Object} success
 * @param {Object} fail
 */
const getNetworkType = function() {
	return new Promise(function(resolve, reject) {
		uni.getNetworkType({
			success: function(res) {
				resolve(res.networkType);
			},
			fail(e) {
				reject(e)
			},
		})
	});
}

/**
 * 拨打电话
 * @param {Object} phoneNumber
 */
const makePhoneCall = function(phoneNumber) {
	return new Promise(function(resolve, reject) {
		uni.makePhoneCall({
			phoneNumber: phoneNumber,
			success: () => {
				resolve(true);
			},
			fail() {
				reject(false);
			},
		});
	});
}

/**
 * 发送短信
 * @param {Object} telTo 电话号码 ['18611497504', '15811140520']
 * @param {Object} msgBody 发送内容 
 * @param {Object} success
 * @param {Object} fail
 */
const sendMessage = function(telTo, msgBody, success, fail) {
	return new Promise(function(resolve, reject) {
		let msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
		msg.to = telTo;
		msg.body = msgBody;
		plus.messaging.sendMessage(msg, (res) => {
			resolve(true);
		}, (e) => {
			reject(false);
		});
	});
}

/**
 * 调起条码扫描
 */
const scanCode = function() {
	return new Promise((resolve, reject) => {
		let self = this;
		let success = function(result) {
			let barcode = result.text;
			if (barcode.indexOf("许可证号：") >= 0) {
				let start = barcode.indexOf("许可证号：") + 5;
				console.log('获取的二维码 start：' + start);
				barcode = barcode.substring(start, start + 12);
				barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
				console.log('获取的二维码 licCode：' + barcode);
			}
			resolve(barcode);
		};
		let fail = function(error) {
			reject("识别失败");
		};
		let par = {
			preferFrontCamera: false, // iOS and Android
			showFlipCameraButton: true, // iOS and Android
			showTorchButton: true, // iOS and Android
			prompt: "请对准二维码/条码,耐心等待", // Android
			resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
			orientation: "portrait", // Android only (portrait|landscape), default unset so it rotates with the device
			disableAnimations: true, // iOS
			disableSuccessBeep: false, // iOS and Android
		};
		cordova.plugins.barcodeScanner.scan(success, fail, par);
	});
}
/**
 *  提示框
 * @param String title 标题
 * @param String content 提示类容
 * @param String confirmText 确定按钮文字
 * @param Boolean showCancel 是否显示取消按钮
 * @param String cancelText 取消按钮文字
 * @param {Object} success
 * @param {Object} fail
 */
const showModal = function(title, content, confirmText, showCancel, cancelText, success, cancel) {
	uni.showModal({
		title: title,
		content: content,
		confirmText: confirmText,
		showCancel: showCancel,
		cancelText: cancelText,
		success: function(res) {
			if (res.confirm) {
				success();
			} else if (res.cancel) {
				cancel();
			}
		},
	})
}

/**
 * 显示操作菜单
 * @param {Object} title 标题 不需要传：""
 * @param {Object} actionbuttons 操作菜单 [{title:"不同意",style:"destructive"},{title:"1"},{title:"2"},{title:"3"}]
 * @param {Object} cancelText 取消按钮文字
 * @param {Object} success 成功回调
 */
const showActionSheet = function(title, actionbuttons, cancelText, success) {
	// #ifdef APP-PLUS
	let actionstyle = {
		title: title,
		cancel: cancelText,
		buttons: actionbuttons,
	};
	plus.nativeUI.actionSheet(actionstyle, function(e) {
		success(e.index);
	});
	// #endif

	// #ifndef APP-PLUS
	let itemList = [];
	for (let i = 0; i < actionbuttons.length; i++) {
		itemList.push(actionbuttons[i].title);
	}
	uni.showActionSheet({
		title: title,
		itemList: itemList,
		cancelText: cancelText,
		success: (e) => {
			console.log(e.tapIndex)
			success(e.tapIndex);
		},
	})
	// #endif
}

/**
 * 获取系统信息
 */
const getSystemInfo = function() {
	return new Promise(function(resolve, reject) {
		uni.getSystemInfo({
			success: function(res) {
				let data = {
					"brand": res.brand,
					"model": res.model,
					"pixelRatio": res.pixelRatio,
					"screenWidth": res.screenWidth,
					"screenHeight": res.screenHeight,
					"system": res.system,
					"platform": res.platform,
				};
				resolve(data);
			},
			fail(e) {
				reject(e);
			},
		});
	});
}

const readFile = function(path) {
	return new Promise((resolve, reject) => {
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024 * 1024, function(fs) {
			fs.root.getFile(path, {
				create: true,
			}, function(fileEntity) {
				readFileEntity(fileEntity).then(
					(file) => {
						resolve(file);
					}, (err) => {
						reject(err);
					})
			});
		});
	});
}

// 读取文件内容
const readFileEntity = function(fileEntry) {
	return new Promise((resolve, reject) => {
		fileEntry.file(function(file) {
			let reader = new FileReader();
			reader.onloadend = function() {
				// 显示文件
				resolve(reader.result);
			}
			reader.readAsArrayBuffer(file);
		}, function(e) {
			reject(e);
		});
	});
}

/**
 *
 * @param {string} path 存储路径
 * @param {Blob} file 存储文件内容
 * @returns {Promise<string>} 实际在访问设备路径
 */
const writeFile = function(path, file) {
	let folderPath = path.substring(0, path.lastIndexOf("/"));
	return new Promise((resolve, reject) => {
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024 * 1024, function(fs) {
			if (folderPath.length > 0) {
				let success = function() {
					createFile(fs, path, file, resolve, reject);
				};
				createFolder(fs, folderPath, success, reject);
			} else {
				createFile(fs, path, file, resolve, reject);
			}
		});
	});
}
const createFolder = function(fs, path, resolve, reject) {
	fs.root.getDirectory(path, {
		create: true,
	}, function(fileEntity) {
		resolve(fileEntity);
	}, function(error) {
		if (error && error.code && error.code == 12) {
			fs.root.getDirectory(path, {
				create: false,
			}, function(fileEntity) {
				resolve(fileEntity);
			});
		} else {
			reject(error);
		}
	});
}

const createFile = function(fs, path, file, resolve, reject) {
	fs.root.getFile(path, {
		create: true,
	}, function(fileEntity) {
		let fileEntityPath = fileEntity.toURL();
		writeFileEntity(fileEntity, file).then(
			() => {
				resolve(fileEntityPath);
			}, (err) => {
				reject(err);
			})
	});
}

// 写入文件
const writeFileEntity = function(fileEntry, content) {
	return new Promise((resolve, reject) => {
		fileEntry.createWriter(function(fileWriter) {
			// 写入结束
			fileWriter.onwriteend = function() {
				resolve();
			};
			fileWriter.onerror = function(e) {
				reject(e);
			};
			fileWriter.write(content);
		});
	});
}

/**
 * 语音录入
 * @param {string} pun 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
 * @returns {Promise<string>} base64 格式
 */
const voice = function(pun) {
	return new Promise((resolve, reject) => {
		let success = function(result) {
			resolve(result);
		};
		let fail = function(error) {
			reject(error);
		};
		window.IFlytekListenVoice.startListen(success, fail, pun);
	});
}

/**
 * 解压缩
 * @param {sourcePath} 文件绝对路径
 * @param {destinationDir}  解压后的输出路径
 * @param {progress}  解压进度函数
 * @returns {Promise<string>} base64 格式
 */
const unzip = function(sourcePath, destinationDir, progress) {
	return new Promise((resolve, reject) => {
		window.zip.unzip(sourcePath, destinationDir, (result) => {
			if (result == 0) {
				resolve();
			} else {
				reject();
			}
		}, progress);
		s
	});
}

let tempEvent = null;

const nfcReader = function() {
	return new Promise((resolve, reject) => {
		let seccess = function(r) {
			// (<any>window).nfc.removeTagDiscoveredListener(this.tempEvent,resolve,reject);
		};
		let callback = function(event) {
			let cardId = event.tag.id.map(function(v, i, arr) {
				let c = v & 0xff;
				return c > 15 ? c.toString(16) : "0" + c.toString(16);
			}).join("").toUpperCase();
			resolve(cardId);
		};

		this.tempEvent = callback;
		window.nfc.enabled((e) => {
			window.nfc.addTagDiscoveredListener(callback, seccess, reject);
		}, (e) => {
			reject(e);
		});
	});
}
const nfcClose = function() {
	return new Promise((resolve, reject) => {
		window.nfc.removeTagDiscoveredListener(this.tempEvent, resolve, reject);
	});
}

const exit = function() {
	navigator.app.exitApp();
}

/**
 * APP 自动更新
 * 对比版本号
 * VERSION_NEED_UPDATE = 201; //检查到需要更新； need update
 * VERSION_UP_TO_UPDATE = 202; //软件是不需要更新；version up to date
 * VERSION_UPDATING = 203; //软件正在更新；version is updating
 * 版本解析错误
 * VERSION_RESOLVE_FAIL = 301; //版本文件解析错误 version-xml file resolve fail
 * VERSION_COMPARE_FAIL = 302; //版本文件对比错误 version-xml file compare fail
 * 网络错误
 * REMOTE_FILE_NOT_FOUND = 404;
 * NETWORK_ERROR = 405;
 * 没有相应的方法
 * NO_SUCH_METHOD = 501;
 * 未知错误
 * UNKNOWN_ERROR = 901;
 * @param {string} updataUrl
 * @returns {Promise<string>}
 */
const appUpdata = function(updataUrl) {
	let pam = {
		'skipPromptDialog': true,
		'skipProgressDialog': true,
	};
	return new Promise(function(resolve, reject) {
		window.AppUpdate.checkAppUpdate(function(rs) {
			resolve(rs.code);
		}, function(error) {
			reject(error);
		}, updataUrl);
	});
}

/**
 * 下载文件到本机并打开
 * @param {string} downloadUrl 下载路径
 * @param {string} file 下载到本地后文件名称
 * @param {string} writePath 本地存储路径
 */
const downLoadFile = function(downloadUrl, file, writePath) {
	let folderPath = '';
	if (writePath) {
		let folderPath = writePath.substring(0, writePath.lastIndexOf("/"));
	}

	return new Promise((resolve, reject) => {
		window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024 * 1024 * 1024, function(fs) {
			// 如果指定文件夹，则放到指定文件夹下
			if (folderPath.length == 0) {
				// 如果没有指定文件夹，则放到cigar_mobile文件夹下
				// folderPath = 'cigar_mobile';
				folderPath = 'cigar_mobile';
			}
			console.log('===' + folderPath);
			// 获取folderPath目录，如果不存在则创建该目录
			fs.root.getDirectory(folderPath, {
				create: true,
			}, function(directoryEntity) {
				// dirEntry

				let filed = formatDate(new Date());
				directoryEntity.getDirectory(filed, {
					create: true,
				}, function(dirEntity) {

					console.log('文件夹获取成功=>directoryEntity.toURL()=>', dirEntity.toURL());

					let dirReader = dirEntity.createReader();
					let entries = [];
					// 返回FileEntry数组
					dirReader.readEntries(function(results) {
						let isExist = false;
						if (results.length > 0) {
							results.map((item) => {
								let fileName = item.toURL();
								if (fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length) ==
									file) {
									isExist = true;
								}
							});
						}
						if (isExist) {
							// 文件存在，直接打开
							getFile(dirEntity, file, downloadUrl, resolve, reject, false);
						} else {
							// 创建文件
							getFile(dirEntity, file, downloadUrl, resolve, reject, true);
						}

					}, function(error) {
						reject('读取文件夹失败：' + JSON.stringify(error));
					});

				}, function(err) {
					reject('文件夹获取失败：' + JSON.stringify(err));
				});

			}, function(error) {
				reject('文件夹获取失败：' + JSON.stringify(error));
			});

		}, function(error) {
			reject('读取文件系统失败：' + JSON.stringify(error));
		});
	});
}

const formatDate = function(date) {
	let y = date.getFullYear();
	console.log(y);
	let m = date.getMonth() + 1;
	m = m < 10 ? '0' + m : m;
	let d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	return y + '-' + m + '-' + d;
}

/**
 * 创建文件
 * @param directoryEntity
 * @param file
 * @param downloadUrl
 * @param resolve
 * @param reject
 */
const getFile = function(directoryEntity, file, downloadUrl, resolve, reject, isCreate) {
	// 创建文件
	directoryEntity.getFile(file, {
		create: isCreate,
		exclusive: false,
	}, function(fileEntity) {
		console.log('文件获取=>fileEntity.toURL()=>', fileEntity.toURL());
		if (isCreate) {
			// 调用下载的方法
			download(fileEntity, downloadUrl, resolve, reject);
		} else {
			openFileWithDialog(fileEntity, resolve, reject);
		}

	}, function(error) {
		reject('文件创建失败：' + JSON.stringify(error));
	});
}

/**
 * 下载文件
 * @param {FileEntry} fileEntry
 * @param {string} url 文件的地址链接
 * @param {boolean} readBinaryData
 */
const download = function(fileEntry, url, resolve, reject) {
	let fileTransfer = new FileTransfer();
	let fileURL = fileEntry.toURL();
	// 监听下载进度
	fileTransfer.onprogress = function(e) {
		console.info(e);
		if (e.lengthComputable) {
			console.log('当前进度：' + e.loaded / e.total);
		}
	}
	console.log('url文件链接地址', url);
	console.log('fileURL', fileURL);
	fileTransfer.download(
		url,
		fileURL,
		function(entry) {
			console.log("Successful download...");
			console.log("download complete: " + entry.toURL());
			openFileWithDialog(entry, resolve, reject);
		},
		function(error) {
			console.log("download error source " + error.source);
			console.log("download error target " + error.target);
			console.log("upload error code" + error.code);
			reject('下载失败：' + JSON.stringify(error));
		},
		null, // or, pass false
		{
			// headers: {
			//    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
			// }
		}
	);
}

/**
 * 打开文件
 * @param {FileEntry} entry
 * @param resolve
 * @param reject
 */
const openFileWithDialog = function(entry, resolve, reject) {
	entry.file(function(data) {
		// showOpenWithDialog使用手机上安装的程序打开下载的文件
		console.log('fileURL打开地址entry.toURL()', entry.toURL());
		console.log('fileURL-data.type', data.type);
		window.cordova.plugins.fileOpener2.showOpenWithDialog(
			decodeURI(entry.toURL()),
			data.type, {
				error: function(error) {
					console.log('打开失败：' + JSON.stringify(error));
					reject('打开失败：' + JSON.stringify(error));
				},
				success: function() {
					resolve('ok');
				},
			}
		);

	});
}

const BAIDU_NAV = {
	'0': "driving", // 驾车
	'1': "transit", // 公交
	'2': "walking", // 步行
	'3': "riding", // 骑行
	'4': "driving", // 火车 百度暂时未提供
	'5': "driving", // 骑行 百度暂时未提供
}

/**
 *  调起高德 ，百度地图服务
 * @param {string} route 服务类型 t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
 * @param {string} dlat 终点纬度
 * @param {string} dlon 终点经度
 * @param {string} slat 起点纬度
 * @param {string} slon 起点经度
 */
const startNavigation = function(route, dlat, dlon, slat, slon) {
	return new Promise((resolve, reject) => {
		showActionSheet("选择", [{
			title: "高德地图",
		}, {
			title: "百度地图",
		}, ], "取消", function(res) {
			let type1 = "";
			if (res === 0) {
				type1 = "amap";
			} else if (res === 1) {
				type1 = "baidu";
			}
			startNav(type1);
		});
		// @param {string} type amap- 高德，baidu-百度
		let startNav = function(type) {
			let success = function(result) {
				resolve(result);
			};
			let fail = function(error) {
				reject(error);
			};
			// 判断平台
			if (util.isAndroid()) {
				// 判断是否是 高德 或者 百度
				if (type == "amap") {
					let uri = '';
					if (slat != undefined && slon != undefined) {
						uri = "amapuri://route/plan/?sourceApplication=移动专卖&slat=" + slat + "&slon=" + slon + "&dlat=" +
							dlat + "&dlon=" + dlon + "&dev=0&t=" + route;
					} else {
						uri = "amapuri://route/plan/?sourceApplication=移动专卖&dlat=" + dlat + "&dlon=" + dlon + "&dev=0&t=" +
							route;

					}
					window.cordovaNaviMap.amapRoute(uri, (res) => {
						success(res)
					}, (err) => {
						fail(err)
					})
				} else if (type == "baidu") {
					let uri = "";
					if (slat != undefined && slon != undefined) {
						uri = 'baidumap://map/direction?origin=' + slat +
							',' + slon + '&destination=' + dlat +
							',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[route] + '&src=com.csbi.monopoly.mobile';
					} else {
						uri = 'baidumap://map/direction?destination=' + dlat +
							',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[route] + '&src=com.csbi.monopoly.mobile';
					}
					window.cordovaNaviMap.bdmapRoute(uri, (res) => {
						success(res)
					}, (err) => {
						fail(err)
					})
				}
			} else if (util.isIOS()) {
				// 判断是否是 高德 或者 百度
				if (type == "amap") {
					let uri = '';
					if (slat != undefined && slon != undefined) {
						uri = "iosamap://path/?sourceApplication=移动专卖&slat=" + slat + "&slon=" + slon + "&dlat=" + dlat +
							"&dlon=" + dlon + "&dev=0&t=" + route;
					} else {
						uri = "iosamap://path/?sourceApplication=移动专卖&dlat=" + dlat + "&dlon=" + dlon + "&dev=0&t=" + route;
					}
					window.cordovaNaviMap.amapRoute(uri, (res) => {
						success(res)
					}, (err) => {
						fail(err)
					})
				} else if (type == "baidu") {
					let uri = 'baidumap://map/navi?location=' + dlat + ',' + dlon + '&coord_type=gcj02&mode=' + BAIDU_NAV[
						route] + '&type=BLK&src=com.csbi.monopoly.mobile';
					window.cordovaNaviMap.bdmapRoute(uri, (res) => {
						success(res)
					}, (err) => {
						fail(err)
					})
				}
			}
		};
	});

}

/**
 * toast弹窗
 */
const toast = (str) => {
	uni.showToast({
		title: str,
	});
};


export default {
	getLocation,
	chooseLocation,
	openLocation,
	getAppVersion,
	getAppVersionCode,
	chooseImage,
	previewImage,
	getNetworkType,
	makePhoneCall,
	sendMessage,
	scanCode,
	showModal,
	showActionSheet,
	getSystemInfo,
	extractThumbnail,
	readFile,
	writeFile,
	voice,
	unzip,
	nfcReader,
	nfcClose,
	exit,
	appUpdata,
	downLoadFile,
	startNavigation,
	labelPrint,
	toast
}